//
//  MoyaNetwork.swift
//  SwiiftProject
//
//  Created by 圣光大人 on 2019/5/10.
//  Copyright © 2019 lazyloading. All rights reserved.
//

import Foundation
import Moya
import HandyJSON


typealias failureBlock = (Any) -> Void

let ZMProvider = initProvider();


func initProvider() -> MoyaProvider<MoyaAPI> {
    return MoyaProvider<MoyaAPI>(
        requestClosure: { (endPoint, closure) in
            do {
                var urlRequest = try endPoint.urlRequest()
                urlRequest.timeoutInterval = 10;
                closure(.success(urlRequest))
            } catch MoyaError.requestMapping(let url) {
                closure(.failure(MoyaError.requestMapping(url)))
            } catch MoyaError.parameterEncoding(let error) {
                closure(.failure(MoyaError.parameterEncoding(error)))
            } catch {
                closure(.failure(MoyaError.underlying(error, nil)))
            }
    })
}

func MoyaRequest<T>( _ api : MoyaAPI ,
                                success : @escaping(BaseResponse<T>) -> Void,
                                failure : failureBlock?)  -> Void {
    
    ZMProvider.request(api) { result in
        switch result{
        case .success(let response):
            do{
                
                let data = try response.mapJSON() as! Dictionary<String, Any>;
                ZMLog("\n--------------------🍭请求完成 Start🍭--------------------\nURL : \(api.baseURL.absoluteString + api.path)\n\nBody : \(data)\n--------------------🍭请求完成 End🍭--------------------");
           
                let successModel = JSONDeserializer<BaseResponse<T>>.deserializeFrom(dict: data);
                if successModel?.respCode == 401 {
                    UserDefaults.standard.removeObject(forKey: kUserInfo);
                    UIApplication.shared.delegate?.window??.rootViewController = BaseNavigationController.init(rootViewController: LoginController());
                }
                success(successModel!);
            }catch {
                if failure != nil  {
                    failure!(error);
                }
                print("源数据解析错误")
            }
            
            break;
        case .failure(let error):
            if failure != nil  {
                failure?(error);
            }
            break;
        }
    }
}




